package com.itheima.rpc.server.boot.nett;

import com.itheima.rpc.netty.codec.FrameDecoder;
import com.itheima.rpc.netty.codec.FrameEncoder;
import com.itheima.rpc.netty.codec.RpcRequestDecoder;
import com.itheima.rpc.netty.codec.RpcResponseEncoder;
import com.itheima.rpc.netty.handler.RpcRequestHandler;
import com.itheima.rpc.server.boot.RpcServer;
import com.itheima.rpc.server.config.RpcServerConfiguration;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.NettyRuntime;
import io.netty.util.concurrent.DefaultThreadFactory;
import io.netty.util.concurrent.EventExecutor;
import io.netty.util.concurrent.UnorderedThreadPoolEventExecutor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Slf4j
@Component
public class NettyServer implements RpcServer {

    @Resource
    private RpcServerConfiguration configuration;

    @Override
    public void start() {
        //创建线程池
        EventLoopGroup boss = new NioEventLoopGroup(1, new DefaultThreadFactory("NettyServerBoss"));
        EventLoopGroup worker = new NioEventLoopGroup(0, new DefaultThreadFactory("NettyServerWorker"));
        EventExecutor business = new UnorderedThreadPoolEventExecutor(NettyRuntime.availableProcessors() * 2, new DefaultThreadFactory("NettyServerBusiness"));

        //创建启动类
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(boss, worker)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .option(ChannelOption.TCP_NODELAY, true)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        pipeline.addLast("FrameEncoder", new FrameEncoder());
                        pipeline.addLast("RpcResponseEncoder", new RpcResponseEncoder());


                        pipeline.addLast("FrameDecoder", new FrameDecoder());
                        pipeline.addLast("RpcRequestDecoder", new RpcRequestDecoder());
                        pipeline.addLast(business, "RpcRequestHandler", new RpcRequestHandler());
                    }
                });

        try {
            //绑定rpc通信端口
            ChannelFuture future = bootstrap.bind(configuration.getRpcPort()).sync();
            //优雅断开连接 释放资源 这种方式不能将线程池关闭写到finally中 不然启动就会关闭 大坑
            future.channel().closeFuture().addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    boss.shutdownGracefully();
                    worker.shutdownGracefully();
                    business.shutdownGracefully();
                }
            });
//            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
            business.shutdownGracefully();
            throw new RuntimeException(e);
        }
    }
}
